'''
读取雷达数据DEMO
张浩
2019-11-23
注：需要安装pyserial库-pip install pyserial
'''
import serial
import matplotlib.pyplot as plt
import numpy as np
import time
from scipy import signal
import pickle

b, a = signal.butter(8, [0.05,0.4], 'bandpass')

with open('C:/Users/姚奕成/OneDrive/桌面/传感技术作业/data/clf.pickle','rb') as f:
    clf2 = pickle.load(f)#从f文件中提取出模型赋给clf2

#定义几项数据
packageLen = 100 #每个数据包100字节，50个采样点
sampleRate = 500 #采样率500Hz
sampleCycle = 1000/sampleRate
startCMD = b"1"
stopCMD = b"0"

#定义缓冲BUFF
buffLen = 1000
dataBUFF = np.zeros(buffLen)

#开启串口
dataSerial = serial.Serial('COM3', baudrate=115200, timeout=100)

#wite for system start
time.sleep(5)

#启动雷达
dataSerial.write(startCMD)

plt.grid(True) # 添加网格
plt.ion()	# interactive mode
plt.figure(1)
plt.xlabel('times')
plt.ylabel('data')
plt.title('Diagram of UART data by Python')
i = 0
count = 0
dataInt = 0
data_get=np.zeros(400)
k=0
pre=0
pre1=0
num=00
#接收数据并绘图
while True:
    if dataSerial.inWaiting() > 0:
        data = dataSerial.read(100)
        ii = 0
        while ii < 100:
            dataInt = int.from_bytes(data[ii:ii+2], byteorder='little', signed = False)
            dataBUFF = dataBUFF.tolist()
            dataBUFF.pop(0)
            dataBUFF.append(dataInt)
            dataBUFF = np.array(dataBUFF)
 #******************************截取信号***************************************

            pre=pre+1
            pre1=pre1+1
            data_normalized=(dataBUFF-min(dataBUFF))/(max(dataBUFF)-min(dataBUFF))
            data_normalized=data_normalized-np.mean(data_normalized)
            data_normalized=abs(data_normalized)
            if pre1>500 and pre>1000 and np.mean(data_normalized[500:520])>0.05 and np.mean(data_normalized[520:540])>0.05\
                    and np.mean(data_normalized[540:560]) > 0.05 and np.mean(data_normalized[480:500])<0.04\
                    and np.mean(data_normalized[460:480])<0.04\
                    and np.mean(data_normalized[440:460]) < 0.04:

                data_get=dataBUFF[450:849] #截取的数据
# *******************************************************************************

                data_filted = signal.filtfilt(b, a, data_get)  # data为要过滤的信号
                f, t, Zxx = signal.stft(data_filted, nperseg=30) #STFT
                Zxx = abs(Zxx)
                Zxx = Zxx.reshape(1, 448)
                #print(clf2.predict(Zxx))
                if clf2.predict(Zxx)==1:
                    print("Left")
                elif clf2.predict(Zxx)==2:
                    print("Right")
                elif clf2.predict(Zxx)==3:
                    print("Push&Pull")
                else:
                    print("Catch")


                k=k+1
                pre1=0
                print(num)

                num=num+1
            ii = ii + 2
        plt.plot(data_get, color='C2')

        plt.show()
        plt.pause(0.0001)
        plt.clf()

dataSerial.write(stopCMD)
